var IMAGE = {
		small_loader : '<img src="/img/small_loader.gif">'
};

$(document).ready(function() {
	
	var validate = (function($){
		var emailRegEx = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		return {
			
			validateSignupForm : function(){
				var signup = {};
				signup.name = $("#signupform #fullName").val();
				signup.userName = $("#signupform #userName").val();
				signup.password = $("#signupform #password").val();
				signup.cpassword = $("#signupform #cpassword").val();
				signup.success = true;
				if (signup.name.length == 0) {
					$("#signupform #fullNameError").css('display', 'block');
					signup.success = false;
				} else {
					$("#signupform #fullNameError").css('display', 'none');
				}

				if (signup.userName.length == 0
						|| !emailRegEx.test(signup.userName)) {
					$("#signupform #userNameError").css('display', 'block');
					signup.success = false;
				} else {
					$("#signupform #userNameError").css('display', 'none');
				}

				if (signup.password.length == 0) {
					$("#signupform #passwordError").css('display', 'block');
					signup.success = false;
				} else {
					$("#signupform #passwordError").css('display', 'none');
				}

				if (signup.password != signup.cpassword && !signup.error) {
					$("#signupform #cpasswordError")
							.css('display', 'block');
					signup.success = false;
				} else {
					$("#signupform #cpasswordError").css('display', 'none');
				}
				return signup.success;
			},
			
			validatePasswordOnlyForm : function(){
				var password = $(".js_password_reset .js_pass").val();
				var cpassword = $(".js_password_reset .js_pass_conf").val();
				if (password != cpassword) {
					$(".js_password_reset .js_cpasswordError").css('display', 'block');
					return false;
				} else {
					$(".js_password_reset .js_cpasswordError").css('display', 'none');
				}
				return true;
			},
			
			validateLogin : function() {
				var userName = $(".js_login_form .js_email").val();
				if (userName.length == 0
						|| !emailRegEx.test(signup.userName)) {
					$(".js_login_form .js_emailError").css('display', 'block');
					return false;
				} else {
					$("..js_login_form .js_emailError").css('display', 'none');
				}
				
				var password = $(".js_login_form #password").val();
				
				if (password.length == 0) {
					$(".js_login_form #passwordError").css('display', 'block');
					return false;
				} else {
					$(".js_login_form #passwordError").css('display', 'none');
				}
				return true;
			},
			
			validateSuccessSignup : function(){
				var flatNo = $(".js_signupsuccess .js_flat").val();
				var phone = $(".js_signupsuccess .js_phone").val();
				if(flatNo.length == 0){
					$(".js_signupsuccess .js_flaterror").css('display', 'block');
					return false;
				} else {
					$(".js_signupsuccess .js_flaterror").css('display', 'none');
				}
				
				if(phone.length == 0){
					$(".js_signupsuccess .js_phoneerror").css('display', 'block');
					return false;
				} else {
					$(".js_signupsuccess .js_phoneerror").css('display', 'none');
				}
				return true;
			}
		};
	})(jQuery);
	
	// binding all forms with respective validators.
	(function($){
		
		// signup button on home page.
		$("#signupform #btn-login").click(function(event){
			if (validate.validateSignupForm()) {
				// submit the form.
				$("#signupform").submit();
			}
			event.preventDefault();
		});
		
		// login button on home page.
		$(".js_login_form #login-btn").click(function(event) {
			if(validate.validateLogin()){
				$(".js_login_form").submit();
			}
		});
		
		//password change page.
		$(".js_password_reset .js_submit").click(function(event) {
			if(validate.validatePasswordOnlyForm()){
				$(".js_password_reset").submit();
			}
		});
		
		$(".js_signupsuccess").find(".js_submit").click(function(){
			if(validate.validateSuccessSignup()){
				$(".js_signupsuccess").submit();
			}
		});
		
	})(jQuery);
	
	// left hand menu.
	
	var discussion = function(){
		
		return {
			
			activate : function(){
				
			},
			deactivate : function(){
				
			}
		};
	};
	
	var info = function(){
		
		return {
			activate : function(){
				
			},
			deactivate : function(){
				
			}
		};
	};
	
	var message = function (){
		
		return {
			activate : function(){
				
			},
			deactivate : function(){
				
			}
		};
	};	
	
	var notice = function (){
		
		return {
			activate : function(){
				
			},
			deactivate : function(){
				
			}
		};
	};
	
	var notification = function (){
		
		return {
			activate : function(){
				
			},
			deactivate : function(){
				
			}
		};
	};
	
	// left menu binding..
	(function(){
		var modules = [dicussion, info, message, notice, notification];
		$('nav.sidebar > ul > li').click(function(){
			$(this).children('ul').show();
			$.each(modules, function(index, module){
				module().deactivate();
			});
			var module = getModule($(this));
			module().activate();
		});
	})();
	
	var template = (function($){
		return {
			'update-form-template' : $("#update-form-template").html(),
			'update-form-rich-txt' : $('#update-form-rich-txt').html(),
			'update-form-rich-txt-tool' : $('#update-form-rich-txt-tool').html(),
			'update-template' : $("#update-template").html(),
			'agenda-update-template-res-no' : $('#agenda-update-template-res-no').html(),
			'agenda-update-template-res-one' :$('#agenda-update-template-res-one').html(),
			'agenda-update-template-res-many' :$('#agenda-update-template-res-many').html(),
			'agenda-update-template' : $('#agenda-update-template').html(),
			'comment-template' : $('#comment-template').html(),
			'agenda-response-yes' : $("#agenda-response-yes").html(),
			'agenda-response-no' : $("#agenda-response-no").html(),
			'comment-template-show-more' : $('#comment-template-show-more').html(),
			'agenda-response-ask-no-comment' : $('#agenda-response-ask-no-comment').html(),
			'agenda-response-ask-with-comment' : $('#agenda-response-ask-with-comment').html(),
			'agenda-update-option' : $('#agenda-update-option').html(),
			'agenda-response-summary' :$('#agenda-response-summary').html(),
			'update-form-template-input' : $('#update-form-template-input').html(),
			'ul-list-wrapper' : $('#ul-list-wrapper').html(),
			'update-form-image-area' : $('#update-form-image-area').html(),
			'update-form-image-item' : $('#update-form-image-item').html(),
		};
	})(jQuery);
	
	var CUSTOM_EVENT = {UPDATE_PAGE : 'UPDATE_PAGE', UPDATE_COMMENT : 'UPDATE_COMMENT'};


	/**
	 * plugins
	 */
	(function($, template){
		
		$.fn.once = function(a, b) {
		    return this.each(function() {
		        $(this).off(a).on(a,b);
		    });
		};
		
		$.empty = function (obj){
			return this.each(function() {
		        return obj === undefined || obj === null || obj.length === 0;
		    });
		};
		
		// dynamic input textbox plugin.
		$.fn.showUpdate = function(options) {
			// merging options together..
			
			// show footer elements;
			// append text area
			var fakeInput = $(this);
			
			var showForm = function(event){
				
				var imageRender = function(files){
					var imageArea = $(template['update-form-image-area']);
					var imageItem = function(file){
						var imageItem = $(Mustache.render(template['update-form-image-item'] , {name : file.name}) );
						return imageItem;
					};
					
					$.each(files, function(index, file){
						var imageHtml = imageItem(file);
						imageArea.append(imageHtml);
						// remove This file item.
						
						imageHtml.find('a:last').click(function(){
							// remove the model.
							files.splice(index,1);
							// remove the view.
							imageHtml.remove();
						});
					});
					return imageArea;
				};
				
				var fakeInputParent = fakeInput.parent();
				var footer = fakeInputParent.siblings('div.panel-footer');
				footer.fadeIn();
				fakeInputParent.empty();
				var div = $(template['update-form-rich-txt']);
				fakeInputParent.append(div);
				div.summernote({
					 focus : true,
					hideToolBar : true,
					  toolbar: [
					            //[groupname, [button list]]
					            ['style', ['bold', 'italic', 'underline', 'clear']],
					            ['font', ['strikethrough']],
					            ['fontsize', ['fontsize']],
					            ['color', ['color']], 
					            ['para', ['ul', 'ol', 'paragraph']],
					            ['height', ['height']],
					          ]
					        });
				var fakeFileInput = footer.find('input[type=file]');
				var files = [];
				var restore = function(){
					footer.hide();
					files = [];
					div.destroy();
					fakeInputParent.empty();
					fakeInputParent.append(fakeInput);
					fakeInput.click(showForm);
				};
				
				var uploadClick = function(){
					fakeFileInput.trigger('click');
				};
				
				footer.find('a.js_showfont').once('click', function(){
					div.showToolBar();
				});
				
				footer.find('a.js_fileupload').once('click', uploadClick);
				
				var imageHtml;
				
				fakeFileInput.once('change', function(event){
					var contains = false;
					$.each(files, function(index, file){
						if(file.name === event.target.files[0].name){
							contains = true;
						}
					});
					if(!contains){
						files.push(event.target.files[0]);
						if(imageHtml){
							imageHtml.remove();
						}
						imageHtml = imageRender(files);
						fakeInputParent.append(imageHtml);
					}
				});
				
				var submitForm = function(){
					var txt = div.code();
					var testCode = txt.replace(/&nbsp;/g,'');
					testCode = testCode.replace(/<p>/g,'');
					testCode = testCode.replace(/<\/p>/g,'');
					testCode = testCode.replace(/<br>/g,'');
					if(testCode.trim().length == 0){
						return;
					}
					var ajaxObj = {};
					if(files.length != 0){
						
						var formData = new FormData();
						$.each(files, function(key, value){
							formData.append('attached[]', value, value.name);
						});
						formData.append('update', txt);
						ajaxObj = {
								url : '/user/update',
								type : "POST",
								data : formData,
								processData: false, // Don't process the files
								contentType: false, // Set content type to false as jQuery will tell the server its a query string request
						};
					} else {
						ajaxObj = {
							url : '/user/update',
							type : "POST",
							data : {update : txt},
						};
					}
					
					fakeInputParent.empty();
					var loader = $(IMAGE.small_loader);
					fakeInputParent.append(loader);
					$.ajax(ajaxObj).done(function() {
						restore();
						$.event.trigger({
							type : CUSTOM_EVENT.UPDATE_PAGE,
							append : false
						}); 
						// update module factory
					}).fail(function() {
						alert('oops ..');
					});
					
				};
				
				footer.find('button.submit').once('click', submitForm);
				footer.find('button.cancel').once('click', function(){
					restore();
				});
				
			};
			
			fakeInput.once('click',showForm);
		};
		
		
		
		// dynamic input textbox plugin.
		$.fn.showCommentInput = function(options) {
			
			var click = function(){
				var form = $(template['update-form-template-input']);
				var fakeInput = $(this);
				fakeInput.after(form);
				fakeInput.remove();
				var area = form.find('textarea');
				if(options.comment){
					area.val(options.comment);
				}
				area.focus();
				if(options.init){
					options.init();
				}
				var restore = function(elem){
					elem.last().after(fakeInput);
					elem.remove();
					fakeInput.click(click);
				};
				
				form.find('button.submit').click(function(){
					if(area.val().trim().length == 0){
						return;
					} else {
						var loader = $(IMAGE.small_loader);
						form.last().after(loader);
						form.remove();
						$.ajax({
							url : '/user/comment',
							type : "POST",
							data : {'comment' : area.val().trim(), 'updateId' : options.parentId},
						}).done(function(data) {
							restore(loader);
							options.callback(data);
							// update module factory
						}).fail(function() {
							alert('oops ..');
						});
					}
				});
				form.find('button.cancel').click(function(){
					if(options.finish){
						options.finish(options);
					}
					restore(form);
				});
			};
			$(this).unbind('click');
			$(this).click(click);
		};
		
		
	})(jQuery, template);

	
	// home page update
	var moduleFactory = (function($, template){
		
		
		var agenda = function(agenda){
			
			// make body of agenda
			var agendaElem =  $(Mustache.render(template['agenda-update-template'], agenda));
			
			// make response.
			var response = function(responses, myResExists){
				
				var responseSummaryLine = $(Mustache.render(template['ul-list-wrapper'], {})); 
					
				var drawRes = function(responses){
					$.each(responses, function(index, response){
						var html = $(Mustache.render(template['agenda-response-yes'], response));
						if(response['answer'] == 'no'){
							html = $(Mustache.render(template['agenda-response-no'], response));
						} 
						responseSummaryLine.append(html);
					});
				};
				
				drawRes(responses.splice(0,2));
				
				if(responses.length > 0){
					var showMore =  $(template['comment-template-show-more']);
					responseSummaryLine.append(showMore);
					showMore.click(function(){
						$(this).remove();
						drawRes(responses);
					});
				}
				return responseSummaryLine;
			};
			
			var responseSummary = function(summary){
				if(summary){
					var summaryBody = $(Mustache.render( template['agenda-response-summary'], {}));
					var normalize = function(response){
						var fullWidth = summaryBody.css('width');
						fullWidth = fullWidth.substr(0,fullWidth.length -2);
						var percentage = parseInt(response)/parseInt(summary.totalResponse);
						return parseInt(fullWidth) * percentage;
					};
						
					var color = ['#ccc','#ddd'];
					
					$.each(summary.result, function(index, item){
						var div = $('<div></div>').css('width',normalize(item.response)).css('background-color', color[index % color.length]).html(item.val+' = '+item.response);
						summaryBody.children('.panel-body').last().append(div);
					});
					return summaryBody;
				}
				
			};
			
			
			var myResponse = function(myresponse, responseForm){
				if(myresponse){
					var responseLine ;
					if(myresponse.comment){
						responseLine = $(Mustache.render( template['agenda-response-ask-with-comment'], myresponse));
					} else {
						responseLine = $(Mustache.render( template['agenda-response-ask-no-comment'], myresponse));
					}
					// click on change answer
					responseLine.find('a span.glyphicon:first').click(function(){
						responseLine.last().after(responseForm(agenda.options, myresponse, myResponse)).fadeIn();
						responseLine.slideUp('slow', function(){
							$(this).remove();
						});
					});
					
					var option;
					if(myresponse.comment){
						var span = responseLine.find('span.comment');
						
						option = { init: function() {span.empty();}, finish : function(option){span.html(option.comment);}, comment : myresponse.comment, callback : function(data){
							span.html(data.comment);
							myresponse['comment'] = data.comment;
							option.comment = data.comment;
							responseLine.find('a:last').showCommentInput(option);
						}};
						
					} else {
						option = { callback : function(data){
								myresponse['comment'] = data.comment;
								var myResponseAfterEditing = myResponse(myresponse, responseForm);
								responseLine.parent().append(myResponseAfterEditing);
								responseLine.remove();
							}
						};
					}
					
					responseLine.find('a:last').showCommentInput(option);
					
					return responseLine;
				}
			};
			
			// response form
			var responseForm = function(options, myresponse, myresponseWidget){
				
				var form = $(Mustache.render(template['agenda-update-option'], {'options':options, 'comment' : myresponse == undefined ? '' : myresponse.comment}));
				if(myresponse){
					var radioQuery = 'input:radio[value='+myresponse.answer+']';
					form.find(radioQuery).attr('checked', true);
				}
				
				form.find('input:radio').click(function(){
					if(myresponse == undefined){
						myresponse = {};
					}
					myresponse['answer'] = $(this).val();
					form.last().after(myresponseWidget(myresponse , responseForm)).fadeIn();
					form.slideUp( "slow", function() {
						$(this).slideUp();
						// Animation complete.
					});
				});
				return form;
			};
			
			if(agenda.meResponded){
				agendaElem.find('div.panel-footer').children('div').first().append(myResponse(agenda.meResponded, responseForm ));
			} else {
				agendaElem.find('div.panel-footer').children('div').first().append(responseForm(agenda.options, agenda.meResponded, myResponse));
			}
			if(agenda.summary){
				//agendaElem.find('div.panel-footer').children('div').last().append(responseSummary(agenda.summary));
			}
			if(agenda.responses){
				agendaElem.append(response(agenda.responses,agenda.meResponded ));
			}
			return agendaElem;
		};
		
		
		var update = function( update){
			var html = $(Mustache.render(template['update-template'], update));
			var ul = html.find(".list-group");
			
			
			var showComment = function(comments){
				ul.empty();
				var removeComment = function(commentId){
						$.ajax({
							url : '/user/deleteComment',
							method : 'POST',
							data : {commentId : commentId}
						}).done(function(data) {
							showComment(data);
							// update module factory
						}).fail(function() {
							alert('oops ..');
						});
				};
				
				var renderComment = function(comment){
					var li = $(Mustache.render(template['comment-template'], comment));
					ul.append(li);
					if(comment.mine){
						li.find('a.js_remove_comment').click(function(){
							removeComment(comment.id);
						});
					} else {
						li.find('a.js_remove_comment').remove();
					}
				};
				
				if(comments){
					var top2Comments = comments.splice(0, 2);
					$.each(top2Comments, function(index, comment){
						renderComment(comment);
					});
					if(comments.length > 0){
						var showMore =  $(template['comment-template-show-more']);
						ul.append(showMore);
						showMore.click(function(){
							$(this).remove();
							$.each(comments, function(index, comment){
								renderComment(comment);
							});
						});
					}
				}
			};
			
			//container.append(html);
			//TODO : not good depends on template.
			html.find(".fakecomment").each(function(){
				$(this).showCommentInput({callback : showComment, parentId : update.upid});
			});
			
			if(update.mine && $.empty(update.comments)()){
				html.find('a.js_remove_update').click(function(){
					$.ajax({
						url : '/user/deleteUpdate',
						method : 'POST',
						data : {updateId : update.upid}
					}).done(function() {
						html.remove();
						// update module factory
					}).fail(function() {
						alert('oops ..');
					});
				});
			} else {
				html.find('a.js_remove_update').remove();
			}
			
			/**
			 * array of comments
			 */
			showComment(update.comments);
			return html;
		};
		
		
		/**
		 * which type of update
		 */
		var moduleFactory = function(data){
			if(data.update_txt){
				return update(data);
			} else if(data.agenda){
				return agenda(data);
			}
			return update;
		};
		return moduleFactory;
	})(jQuery, template);

	var pageDS = {lastSeenId : 0};
	
	/**
	 * Updating the profile page.
	 */
	$('#fileupload').change(function() {
		if (this.files && this.files[0]) {
			$('#profile-upload-preview').css('display', 'block').attr('src', $(this).result);
	        var reader = new FileReader();
	        reader.onload = function (e) {
	            $('#profile-upload-preview').attr('src', e.target.result);
	        };
	        reader.readAsDataURL(this.files[0]);
	    }
	});
	
	/**
	 * dynamic form binding.
	 */
	$("#updateInput").showUpdate({});
	$(".fakecomment").each(function(){
		//$(this).showInput({});
	});
	
	$(document).on(CUSTOM_EVENT.UPDATE_PAGE, function(event){
		if(event.append){
			
			/**
			 * update on home page.
			 */
			$.ajax({url : '/user/getUpdate', data : {lastSeenId : pageDS.lastSeenId}}).done(function(data){
				$.each(data, function(index, value){
					$(".main-content").children('.update-area').append(moduleFactory(value)).slideDown();
					if(pageDS.lastSeenId < value.upid){
						pageDS.lastSeenId = value.upid;
					}
				});
			});
			
		} else {
			
			/**
			 * update on home page.
			 */
			$.ajax({url : '/user/getUpdate', data : {lastSeenId : pageDS.lastSeenId}}).done(function(data){
				$.each(data, function(index, value){
					 $(".main-content").children('.update-area').prepend(moduleFactory(value)).slideDown();
					 if(pageDS.lastSeenId < value.upid){
							pageDS.lastSeenId = value.upid;
					 }
				});
			});
		}
	});
	
	$.event.trigger({
		type : CUSTOM_EVENT.UPDATE_PAGE,
		append : true
	}); 
	
	
});
